# encoding:utf-8

import requests
import base64
import json
from com.watermelon.rpa.functions import invoice_config


def obtain_Access_token():
    url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={invoice_config.API_Key}&client_secret={invoice_config.Secret_Key}"

    payload = ""
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    return json.loads(response.text)

#print(obtain_Access_token())

def invoice_identify(token,filePath,fileType):
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice"
    # 二进制方式打开图片文件
    f = open(filePath, 'rb')
    img = base64.b64encode(f.read())

    params = {fileType: img}
    access_token = token
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        return response.json()

access_token = obtain_Access_token()["access_token"]

filePath = r"D:\sutdy-Rpa-file\13课\滴滴电子发票A.pdf"
result = invoice_identify(access_token,filePath,"pdf_file")

print(result["words_result"])